﻿/**
*
*  RSSReader is a lightweight RSS client written in C#
*
*  Copyright 2012 Ashot Aslanyan <ashot.aslanian@gmail.com>
*
*  This file is part of RSSReader.
*
*  RSSReader is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  RSSReader is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with servmonitor.  If not, see <http://www.gnu.org/licenses/>.
*
*/

using System;
using System.Net;
using System.Windows.Forms;

namespace RSSReader
{
    class InputMessageBox : Form
    {
        private Label TextLabel;
        private TextBox FeedUrl;
        private Button OKButton;

        public string url { get { return this.FeedUrl.Text; } }

        public InputMessageBox()
        {
            this.InitializeComponent();
        }
    
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InputMessageBox));
            this.TextLabel = new System.Windows.Forms.Label();
            this.FeedUrl = new System.Windows.Forms.TextBox();
            this.OKButton = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // TextLabel
            // 
            this.TextLabel.Location = new System.Drawing.Point(10, 15);
            this.TextLabel.Name = "TextLabel";
            this.TextLabel.Size = new System.Drawing.Size(360, 20);
            this.TextLabel.TabIndex = 0;
            this.TextLabel.Text = "URL of feed:";
            // 
            // FeedUrl
            // 
            this.FeedUrl.Location = new System.Drawing.Point(10, 50);
            this.FeedUrl.Name = "FeedUrl";
            this.FeedUrl.Size = new System.Drawing.Size(360, 20);
            this.FeedUrl.TabIndex = 1;
            // 
            // OKButton
            // 
            this.OKButton.Location = new System.Drawing.Point(160, 110);
            this.OKButton.Name = "OKButton";
            this.OKButton.Size = new System.Drawing.Size(80, 30);
            this.OKButton.TabIndex = 2;
            this.OKButton.Text = "OK";
            this.OKButton.UseVisualStyleBackColor = true;
            this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
            // 
            // InputMessageBox
            // 
            this.ClientSize = new System.Drawing.Size(394, 152);
            this.Controls.Add(this.OKButton);
            this.Controls.Add(this.FeedUrl);
            this.Controls.Add(this.TextLabel);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "InputMessageBox";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Add new feed";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        void OKButton_Click(object sender, EventArgs e)
        {
            if (this.UrlIsValid(this.url))
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                this.DialogResult = DialogResult.None;
                MessageBox.Show("Seems not valid url. Please check spelling and try again.");
            }
        }

        /// <summary>
        /// This method will check a url to see that it does not return server or protocol errors
        /// </summary>
        /// <param name="url">The path to check</param>
        /// <returns>If <paramref name="url"/> is valid or not</returns>
        private bool UrlIsValid(string url)
        {
            try
            {
                HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
                request.Timeout = 5000; //set the timeout to 5 seconds to keep the user from waiting too long for the page to load
                request.Method = "HEAD"; //Get only the header information -- no need to download any content

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                int statusCode = (int)response.StatusCode;
                if (statusCode >= 100 && statusCode < 400) //Good requests
                {
                    return true;
                }
                else if (statusCode >= 500 && statusCode <= 510) //Server Errors
                {
                    Logger.Instance.Log("InputMessageBox", 
                        String.Format("The remote server has thrown an internal error. Url is not valid: {0}", url));
                    return false;
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError) //400 errors
                {
                    return false;
                }
                else
                {
                    Logger.Instance.Log("InputMessageBox", 
                        String.Format("Unhandled status [{0}] returned for url: {1}", ex.Status, url));
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Log("InputMessageBox", String.Format("Could not test url {0}.\n {1}", url, ex.Message));
            }
            return false;
        }
    }
}
